/* Generic Windows Process Patcher. Intended for patching nedmalloc in to
replace the MSVCRT allocator but could be used for anything.
(C) 2009-2010 Niall Douglas

Boost Software License - Version 1.0 - August 17th, 2003

Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:

The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/

/*#define _DEBUG
#define USE_DEBUGGER_OUTPUT
#pragma optimize("g", off)*/

#ifdef NEDMALLOC_DLL_EXPORTS /* Building patcher with nedmalloc */
#include "nedmalloc.h"
extern void *(*sysmalloc)(size_t);
extern void *(*syscalloc)(size_t, size_t);
extern void *(*sysrealloc)(void *, size_t);
extern void (*sysfree)(void *);
extern size_t (*sysblksize)(void *);
#else                        /* Else building patcher with dlmalloc */
#ifndef NEDMALLOCEXTSPEC
 #if defined(NEDMALLOC_DLL_EXPORTS) || defined(USERMODEPAGEALLOCATOR_DLL_EXPORTS)
  #ifdef WIN32
   #define NEDMALLOCEXTSPEC extern __declspec(dllexport)
  #elif defined(__GNUC__)
   #define NEDMALLOCEXTSPEC extern __attribute__ ((visibility("default")))
  #endif
  #ifndef ENABLE_TOLERANT_NEDMALLOC
   #define ENABLE_TOLERANT_NEDMALLOC 1
  #endif
 #else
  #define NEDMALLOCEXTSPEC extern
 #endif
#endif
#define nedpmalloc(a, v) HeapAlloc(GetProcessHeap(), 0, (v))
#define nedpcalloc(a, v, s) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (v)*(s))
#define nedprealloc(a, p, v) HeapReAlloc(GetProcessHeap(), 0, (p), (v))
#define nedpfree(a, p) HeapFree(GetProcessHeap(), 0, (p))
#endif
#include "embedded_printf.h"
#include <stdlib.h>
#include <assert.h>
#ifdef WIN32
#include <tchar.h>
#include <process.h>
#include <malloc.h>
#ifdef USERMODEPAGEALLOCATOR_DLL_EXPORTS
#define ENABLE_USERMODEPAGEALLOCATOR 1
#define THROWSPEC
#define ONLY_MSPACES 1
#define MMAP_CLEARS 0
#include "malloc.c.h"
#include "usermodepageallocator.c"
#else
#define WIN32_LEAN_AND_MEAN 1
#define _WIN32_WINNT 0x0501		/* Minimum of Windows XP required */
#include <windows.h>
#endif
#include "Dbghelp.h"
#pragma comment(lib, "dbghelp.lib")
#include <psapi.h>
#include "nedtries/uthash/src/uthash.h"
#include "winpatcher_errorh.h"

#pragma warning(disable: 4100)	/* Unreferenced formal parameter */
#pragma warning(disable: 4127)	/* conditional expression is constant */
#pragma warning(disable: 4706)	/* Assignment within conditional expression */

/* TODO list:

* Patch GetProcAddress to return the patched address
*/

/* Set uthash to use nedmalloc */
#undef uthash_malloc
#undef uthash_free
#define uthash_malloc(sz) nedpmalloc(0, sz)
#define uthash_free(ptr, sz) nedpfree(0, ptr)
#define HASH_FIND_PTR(head,findptr,out)                                         \
    HASH_FIND(hh,head,findptr,sizeof(void *),out)
#define HASH_ADD_PTR(head,ptrfield,add)                                         \
    HASH_ADD(hh,head,ptrfield,sizeof(void *),add)

#if defined(__cplusplus)
#if !defined(NO_WINPATCHER_NAMESPACE)
namespace winpatcher {
#else
extern "C" {
#endif
#endif

/* If you want to learn lots more about the vagueries of Win32 PE dynamic linking,
see http://msdn.microsoft.com/en-us/magazine/cc301808.aspx. Excerpt from that:

The anchor of the imports data is the IMAGE_IMPORT_DESCRIPTOR structure. The DataDirectory
entry for imports points to an array of these structures. There's one IMAGE_IMPORT_DESCRIPTOR
for each imported executable. The end of the IMAGE_IMPORT_DESCRIPTOR array is indicated by an
entry with fields all set to 0. Figure 5 shows the contents of an IMAGE_IMPORT_DESCRIPTOR.

Each IMAGE_IMPORT_DESCRIPTOR typically points to two essentially identical arrays. These
arrays have been called by several names, but the two most common names are the Import Address
Table (IAT) and the Import Name Table (INT).

Both arrays have elements of type IMAGE_THUNK_DATA, which is a pointer-sized union. Each
IMAGE_THUNK_DATA element corresponds to one imported function from the executable. The ends of
both arrays are indicated by an IMAGE_THUNK_DATA element with a value of zero. The
IMAGE_THUNK_DATA union is a DWORD with these interpretations:

DWORD Function;       // Memory address of the imported function
DWORD Ordinal;        // Ordinal value of imported API
DWORD AddressOfData;  // RVA to an IMAGE_IMPORT_BY_NAME with
                      // the imported API name
DWORD ForwarderString;// RVA to a forwarder string

The IMAGE_THUNK_DATA structures within the IAT lead a dual-purpose life. In the executable
file, they contain either the ordinal of the imported API or an RVA to an IMAGE_IMPORT_BY_NAME
structure. The IMAGE_IMPORT_BY_NAME structure is just a WORD, followed by a string naming the
imported API. The WORD value is a "hint" to the loader as to what the ordinal of the imported
API might be. When the loader brings in the executable, it overwrites each IAT entry with the
actual address of the imported function. This a key point to understand before proceeding. I
highly recommend reading Russell Osterlund's article in this issue which describes the steps
that the Windows loader takes.

Before the executable is loaded, is there a way you can tell if an IMAGE_THUNK_DATA structure
contains an import ordinal, as opposed to an RVA to an IMAGE_IMPORT_BY_NAME structure? The key
is the high bit of the IMAGE_THUNK_DATA value. If set, the bottom 31 bits (or 63 bits for a 64-bit
executable) is treated as an ordinal value. If the high bit isn't set, the IMAGE_THUNK_ DATA value
is an RVA to the IMAGE_IMPORT_BY_NAME.

The other array, the INT, is essentially identical to the IAT. It's also an array of
IMAGE_THUNK_DATA structures. The key difference is that the INT isn't overwritten by the loader
when brought into memory. Why have two parallel arrays for each set of APIs imported from a DLL?
The answer is in a concept called binding. When the binding process rewrites the IAT in the file
(I'll describe this process later), some way of getting the original information needs to remain.
The INT, which is a duplicate copy of the information, is just the ticket.
*/


typedef struct ModuleListItem_t
{
	const char *into;
	HMODULE intoAddr;
	const char *from;	/* zero means this module */
} ModuleListItem;

typedef struct SymbolListItem_t
{
	struct Replace_t
	{
		const char *name;				/* Replace this symbol */
		HMODULE moduleBase;				/* In this DLL */
		char moduleName[_MAX_PATH+2];	/* Where the DLL is named this */
		PROC addr;						/* Where the symbol has this address in the DLL (=0 for use GetProcAddress()) */
	} replace;
	ModuleListItem *modules;			/* zero means wherever the replace symbol lives */
	struct With_t
	{
		const char *name;
		PROC addr;
	} with;
} SymbolListItem;


/* Little helper function to return the module base (a HMODULE)
given some address within that module. Assumes that the NT kernel
maps an entire module at once with one TLB entry */
static HMODULE ModuleFromAddress(void *addr) THROWSPEC
{
	MEMORY_BASIC_INFORMATION mbi={0};
	return ((VirtualQuery(addr, &mbi, sizeof(mbi)) != 0) ? (HMODULE) mbi.AllocationBase : NULL);
}

/* Little helper function to deindirect the PE DLL linking mechanism
This is architecture dependent */
static PROC DeindirectAddress(PROC _addr) THROWSPEC
{
	unsigned char *addr=(unsigned char *)((size_t) _addr);
#if defined(_M_IX86)
	if(0xe9==addr[0])
	{	/* We're seeing a jmp rel32 inserted under Edit & Continue */
		unsigned int offset=*(unsigned int *)(addr+1);
		addr+=offset+5;
	}
	if(0xff==addr[0] && 0x25==addr[1])
	{	/* This is a jmp ptr, so dword[2:6] is where to load the address from */
		addr=(unsigned char *)(**(unsigned int **)(addr+2));
	}
#elif defined(_M_X64)
	if(0xff==addr[0] && 0x25==addr[1])
	{	/* This is a jmp qword ptr, so dword[2:6] is the offset to where to load the address from */
		unsigned int offset=*(unsigned int *)(addr+2);
		addr+=offset+6;
		addr=(unsigned char *)(*(size_t *)(addr));
	}
#endif
	return (PROC)(size_t) addr;
}

/* Little helper function for sending stuff to the debugger output
seeing as fprintf et al are completely unavailable to us */
#if defined(_DEBUG) && defined(USE_DEBUGGER_OUTPUT)
#include "embedded_printf.c"
#endif
static void putc_(void *p, char c) THROWSPEC { *(*((char **)p))++ = c; }
static HANDLE debugfile=INVALID_HANDLE_VALUE;
extern void DebugPrint(const char *fmt, ...) THROWSPEC
{
#if defined(_DEBUG) && defined(USE_DEBUGGER_OUTPUT)
	char buffer[16384];
	char *s=buffer;
	HANDLE stdouth=GetStdHandle(STD_OUTPUT_HANDLE);
	DWORD len;
	DWORD written=0;

	va_list va;
	va_start(va,fmt);
	tfp_format(&s,putc_,fmt,va);
	putc_(&s,0);
	va_end(va);
	len=(DWORD)(strchr(buffer, 0)-buffer);
	OutputDebugStringA(buffer);
	if(stdouth && stdouth!=INVALID_HANDLE_VALUE)
		WriteFile(stdouth, buffer, len, &written, NULL);
#if 1	/* Enable this if you want it to write the log to C:\nedmalloc.log */
	if(INVALID_HANDLE_VALUE==debugfile)
	{
		debugfile=CreateFile(__T("C:\\nedmalloc.log"), GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, 
			NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	}
	if(INVALID_HANDLE_VALUE!=debugfile)
		WriteFile(debugfile, buffer, len, &written, NULL);
#endif
#endif
}

/* Traps win32 structured exceptions and converts to Status */
static int ExceptionToStatus(Status *ret, unsigned int code, EXCEPTION_POINTERS *ep)
{
#if defined(_DEBUG)
	DebugPrint("Winpatcher: Win32 Exception %u at %p\n", code, ep->ExceptionRecord ? ep->ExceptionRecord->ExceptionAddress : 0);
#endif
	ret->code=-(int)code;
	_stprintf_s(ret->msg, sizeof(ret->msg)/sizeof(TCHAR), __T("Win32 Exception %u at %p"), code, ep->ExceptionRecord ? ep->ExceptionRecord->ExceptionAddress : 0);
	return EXCEPTION_EXECUTE_HANDLER;
}

/* Our own implementation of DbgHelp's ImageDirectoryEntryToData()
DbgHelp unfortunately calls malloc() during its DllMain which is a
big no-no in our situation */
PVOID MyImageDirectoryEntryToData(PVOID Base, BOOLEAN MappedAsImage, USHORT DirectoryEntry, PULONG Size )
{
	IMAGE_DOS_HEADER *dosheader=(IMAGE_DOS_HEADER *) Base;
	IMAGE_NT_HEADERS *peheader=0;
	void *ret=0;
	size_t offset=0;
	if(Size) *Size=0;
	if(dosheader->e_magic==*(USHORT *)"MZ")
		peheader=(IMAGE_NT_HEADERS *)((char *)dosheader+dosheader->e_lfanew);
	else
		peheader=(IMAGE_NT_HEADERS *) dosheader;
	if(peheader->Signature!=IMAGE_NT_SIGNATURE)
	{
		SetLastError(ERROR_INVALID_DATA);
		return 0;
	}
	offset=peheader->OptionalHeader.DataDirectory[DirectoryEntry].VirtualAddress;
	if(offset)
	{
		ret=(void *)((char *) Base+offset);
		if(Size) *Size=peheader->OptionalHeader.DataDirectory[DirectoryEntry].Size;
	}
	return ret;
}


/* Modifies the import table of a loaded module
     Returns: The number of entries modified
     moduleBase: Where the PE module is living in memory
     importModuleName: Name of the PE module whose exports we wish to modify
	 fnToReplace: Address of function to replace
	 fnNew: Replacement address
*/
static Status ModifyModuleImportTableForI(HMODULE moduleBase, const char *importModuleName, SymbolListItem *sli, int patchin) THROWSPEC
{
	Status ret = { SUCCESS };
	ULONG size;
	PIMAGE_THUNK_DATA thunk = 0;
	PIMAGE_IMPORT_DESCRIPTOR desc = 0;
	PROC replaceaddr = patchin ? sli->replace.addr : sli->with.addr, withaddr = patchin ? sli->with.addr : sli->replace.addr;
	int replaced = 0;

	/* Find the import table of the module loaded at hmodCaller */
	desc = (PIMAGE_IMPORT_DESCRIPTOR) MyImageDirectoryEntryToData(moduleBase, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &size);
	if (!desc)
		return MKSTATUS(ret, SUCCESS);  /* This module has no import section */

	/* Find all import descriptors containing references to the module we want. */
	for (; desc->Name; desc++) {
		PSTR modname = (PSTR)((PBYTE) moduleBase + desc->Name);
		int modnamecmp = lstrcmpiA(modname, importModuleName);
		/*if (modnamecmp>0) 
			break;*/
		if (0==modnamecmp) {
			/* Get the import address table (IAT) for the functions imported from our wanted module */
			thunk = (PIMAGE_THUNK_DATA)((PBYTE) moduleBase + desc->FirstThunk);

			/* Find and replace current function address with new function address */
			for (; thunk->u1.Function; thunk++) {
				/* Get the address of the function address */
				PROC *fn = (PROC *) &thunk->u1.Function;

				/* Is this the function we're looking for? */
				BOOL found = (*fn == replaceaddr);

				if (found) {
					/* The addresses match; change the import section address. */
					MEMORY_BASIC_INFORMATION mbi={0};
		#if defined(_DEBUG)
					{
						char moduleBaseName[_MAX_PATH+2];
						GetModuleBaseNameA(GetCurrentProcess(), moduleBase, moduleBaseName, sizeof(moduleBaseName)-1);
						DebugPrint("Winpatcher: Replacing function pointer %p (%s:%s) with %p (%s) at %p in module %p (%s)\n",
								*fn, importModuleName, sli->replace.name, withaddr, sli->with.name, fn, moduleBase, moduleBaseName);
					}
		#endif
					/*if(!WriteProcessMemory(GetCurrentProcess(), fn, &withaddr, sizeof(withaddr), NULL))
					return MKSTATUSWIN(ret);*/
					if(!VirtualQuery(fn, &mbi, sizeof(mbi)))
						return MKSTATUSWIN(ret);
					if(!(mbi.Protect & PAGE_EXECUTE_READWRITE))
					{
		#if defined(_DEBUG)
						DebugPrint("Winpatcher: Setting PAGE_WRITECOPY on module %p, region %p length %u\n", moduleBase, mbi.BaseAddress, mbi.RegionSize);
		#endif
						if(!VirtualProtect(mbi.BaseAddress, mbi.RegionSize, PAGE_EXECUTE_WRITECOPY, &mbi.Protect))
							return MKSTATUSWIN(ret);
					}
					*fn=withaddr;
					FlushInstructionCache(GetCurrentProcess(), mbi.BaseAddress, mbi.RegionSize);
					if(!VirtualProtect(mbi.BaseAddress, mbi.RegionSize, PAGE_EXECUTE_READ, &mbi.Protect))
						return MKSTATUSWIN(ret);
					replaced++;
				}
			}
		}
	}
	return MKSTATUS(ret, SUCCESS+replaced);
}

/* Modifies all symbols in the import table of a loaded module
     Returns: The number of entries modified
     moduleBase: The PE module to patch
*/
static Status ModifyModuleImportTableFor(HMODULE moduleBase, SymbolListItem *sli, int patchin, int *usingreleaseMSVCRT, int *usingdebugMSVCRT) THROWSPEC
{
	Status ret={SUCCESS};
	int count=0;
	for(; sli->replace.name; sli++, count++)
	{
		if(sli->modules)
		{
			ModuleListItem *module;
			int moduleidx=0;
			for(module=sli->modules; module->into; module++, moduleidx++)
			{
				if(!module->intoAddr && (HMODULE)(size_t)-1!=module->intoAddr)
				{
					if(!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module->into, &module->intoAddr))
						module->intoAddr=(HMODULE)(size_t)-1;
				}
				if((HMODULE)(size_t)-1==module->intoAddr)
				{	/* Not loaded so move to next one */
					ret=MKSTATUSWIN(ret);
					continue;
				}
				sli->replace.moduleBase=module->intoAddr;
				if(!(sli->replace.addr=GetProcAddress(sli->replace.moduleBase, sli->replace.name)))
					return MKSTATUS(ret, SUCCESS); /* Some symbols may not always be found */
				if(!module->from)
				{
					if(!sli->with.addr)
						abort();	/* If we are not specifying the module it must be a local symbol */
				}
				else
				{
					HMODULE withBase=0;
					if(!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module->from, &withBase))
						return MKSTATUSWIN(ret);
					if(!(sli->with.addr=GetProcAddress(withBase, sli->with.name)))
						return MKSTATUSWIN(ret);
				}
				if((ret=ModifyModuleImportTableForI(moduleBase, module->into, sli, patchin), ret.code)<0)
					return ret;
				if(ret.code && !strncmp(module->into, "MSVCR", 5))
				{
					if(usingdebugMSVCRT && (moduleidx & 1)) (*usingdebugMSVCRT)++;
					else (*usingreleaseMSVCRT)++;
				}
			}
		}
		else
		{
			if(!sli->replace.moduleBase)
			{
				if(!sli->replace.addr || !sli->with.addr)
					abort();	/* If you are not specifying modules you must specify symbols */
				sli->replace.addr=DeindirectAddress(sli->replace.addr);
				sli->replace.moduleBase=ModuleFromAddress((void *)(size_t) sli->replace.addr);
				if(!GetModuleBaseNameA(GetCurrentProcess(), sli->replace.moduleBase, sli->replace.moduleName, sizeof(sli->replace.moduleName)-1))
					return MKSTATUSWIN(ret);
			}
			if((ret=ModifyModuleImportTableForI(moduleBase, sli->replace.moduleName, sli, patchin), ret.code)<0)
				return ret;
		}
	}
	return MKSTATUS(ret, count);
}


/* ARA are suffering from slow process init times due to the patcher. Let's see what we can
do through the magic of caching! */
static HMODULE MyModuleBase, skipModules[3], lastModuleList[4096];
static DWORD lastModuleListLen;
typedef struct PatchedModule_t
{
	HMODULE moduleBaseAddr;
	char moduleBaseName[_MAX_PATH+2];
	UT_hash_handle hh;
} PatchedModule;
static PatchedModule *patchedmodules;
/* Modifies all symbols in all loaded modules
     Returns: The number of entries modified, plus how many are using release vs. debug versions of MSVCRT
*/
NEDMALLOCEXTSPEC Status WinPatcher(SymbolListItem *symbollist, int patchin, int *usingreleaseMSVCRT, int *usingdebugMSVCRT) THROWSPEC;
Status WinPatcher(SymbolListItem *symbollist, int patchin, int *usingreleaseMSVCRT, int *usingdebugMSVCRT) THROWSPEC
{
	int count=0;
	Status ret={SUCCESS};
	__try
	{
		HMODULE *module=0, modulelist[4096];
		DWORD modulelistlen=sizeof(modulelist), modulelistlenneeded=0;

		if(!skipModules[0])
		{
			assert(MyModuleBase);
			skipModules[0]=ModuleFromAddress((void *)(size_t) StackWalk64); /* Not DbgHelp.dll as it calls malloc during its own operation which causes recursion */
		}
		/* This is not a fast call, but sadly there is no choice */
		if(!EnumProcessModules(GetCurrentProcess(), modulelist, modulelistlen, &modulelistlenneeded))
			return MKSTATUSWIN(ret);
		if(!patchin || lastModuleListLen!=modulelistlenneeded || memcmp(lastModuleList, modulelist, modulelistlenneeded))
		{
			for(module=modulelist; module<modulelist+(modulelistlenneeded/sizeof(HMODULE)); module++)
			{
				PatchedModule *pm=0;
				HMODULE *m;
				HASH_FIND_PTR(patchedmodules, module, pm);
				if(pm)
				{	/* Already patched */
					assert(pm->moduleBaseAddr==*module);
#if defined(_DEBUG)
					DebugPrint("Winpatcher: Module %p (%s) already patched\n", pm->moduleBaseAddr, pm->moduleBaseName, patchin ? "patch" : "depatch");
#endif
					if(patchin)
					{
						count+=SUCCESS;
						continue;
					}
				}
				else
				{
					if(!(pm=nedpcalloc(0, 1, sizeof(PatchedModule))))
						return MKSTATUS(ret, ERROR);
					pm->moduleBaseAddr=*module;
#if defined(_DEBUG)
					/* This is an extremely slow call, so absolutely avoid if possible */
					GetModuleBaseNameA(GetCurrentProcess(), pm->moduleBaseAddr, pm->moduleBaseName, sizeof(pm->moduleBaseName)-1);
#endif
					HASH_ADD_PTR(patchedmodules, moduleBaseAddr, pm);
				}
				if(*module==MyModuleBase || *module==skipModules[0])
					continue;	/* Not us or we'd break our patch table */
#if defined(_DEBUG)
				DebugPrint("Winpatcher: Scanning module %p (%s) for things to %s ...\n", pm->moduleBaseAddr, pm->moduleBaseName, patchin ? "patch" : "depatch");
#endif
				if((ret=ModifyModuleImportTableFor(*module, symbollist, patchin, usingreleaseMSVCRT, usingdebugMSVCRT), ret.code)<0)
					return ret;
				count+=ret.code;
			}
			memcpy(lastModuleList, modulelist, modulelistlenneeded);
			lastModuleListLen=modulelistlenneeded;
		}
		else
		{
#if defined(_DEBUG)
			DebugPrint("Winpatcher: Loaded module list hasn't changed, so exiting\n");
#endif
		}
	}
	__except(ExceptionToStatus(&ret, GetExceptionCode(), GetExceptionInformation()))
	{
		return ret;
	}
	return MKSTATUS(ret, count);
}












NEDMALLOCEXTSPEC int PatchInNedmallocDLL(void) THROWSPEC;
NEDMALLOCEXTSPEC int DepatchInNedmallocDLL(void) THROWSPEC;
/* A LoadLibrary() wrapper. It's important to patch before
as well as after as one DLL load can trigger other DLL loads */
static HMODULE WINAPI LoadLibraryA_winpatcher(LPCSTR lpLibFileName)
{
	HMODULE ret=0;
#ifdef REPLACE_SYSTEM_ALLOCATOR
	/*if(!PatchInNedmallocDLL()) abort();*/
#endif
#if defined(_DEBUG)
	DebugPrint("Winpatcher: LoadLibraryA intercepted\n");
#endif
	ret=LoadLibraryA(lpLibFileName);
#ifdef REPLACE_SYSTEM_ALLOCATOR
	if(!PatchInNedmallocDLL()) abort();
#endif
	return ret;
}
static HMODULE WINAPI LoadLibraryW_winpatcher(LPCWSTR lpLibFileName)
{
	HMODULE ret=0;
#ifdef REPLACE_SYSTEM_ALLOCATOR
	/*if(!PatchInNedmallocDLL()) abort();*/
#endif
#if defined(_DEBUG)
	DebugPrint("Winpatcher: LoadLibraryW intercepted\n");
#endif
	ret=LoadLibraryW(lpLibFileName);
#ifdef REPLACE_SYSTEM_ALLOCATOR
	if(!PatchInNedmallocDLL()) abort();
#endif
	return ret;
}
#if ENABLE_USERMODEPAGEALLOCATOR
#define M2_CUSTOM_FLAGS_BEGIN   (1<<16)
#define USERPAGE_TOPDOWN                   (M2_CUSTOM_FLAGS_BEGIN<<0)
#define USERPAGE_NOCOMMIT                  (M2_CUSTOM_FLAGS_BEGIN<<1)
extern int OSHavePhysicalPageSupport(void);
extern void *userpage_malloc(size_t toallocate, unsigned flags);
extern int userpage_free(void *mem, size_t size);
extern void *userpage_realloc(void *mem, size_t oldsize, size_t newsize, int flags, unsigned flags2);
extern void *userpage_commit(void *mem, size_t size);
extern int userpage_release(void *mem, size_t size);
static LPVOID WINAPI VirtualAlloc_winpatcher(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect)
{
	LPVOID ret=0;
	dwSize=(dwSize+4095) & ~4095;
#if defined(_DEBUG)
	DebugPrint("Winpatcher: VirtualAlloc(%p, %u, %x, %x) intercepted\n", lpAddress, dwSize, flAllocationType, flProtect);
#endif
	if(OSHavePhysicalPageSupport())
	{
		if(!lpAddress && flAllocationType&MEM_RESERVE)
		{
			ret=userpage_malloc(dwSize, (flAllocationType&MEM_COMMIT) ? 0 : USERPAGE_NOCOMMIT);
	#if defined(_DEBUG)
			DebugPrint("Winpatcher: userpage_malloc returns %p\n", ret);
			if(flAllocationType&MEM_COMMIT)
			{
				volatile char *p, *pend=(char *) ret + dwSize;
				for(p=(char *) ret; p<pend; p+=4096)
					*p;
			}
	#endif
		}
		else if(lpAddress && (flAllocationType&(MEM_COMMIT|MEM_RESERVE))==(MEM_COMMIT))
		{
			ret=userpage_commit(lpAddress, dwSize);
	#if defined(_DEBUG)
			DebugPrint("Winpatcher: userpage_commit returns %p\n", ret);
	#endif
		}
	}
	if(!ret || (void *)-1==ret)
	{
		ret=VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect);
#if defined(_DEBUG)
		DebugPrint("Winpatcher: VirtualAlloc returns %p\n", ret);
#endif
	}
	return (void *)-1==ret ? 0 : ret;
}
static BOOL WINAPI VirtualFree_winpatcher(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType)
{
	dwSize=(dwSize+4095) & ~4095;
#if defined(_DEBUG)
	DebugPrint("Winpatcher: VirtualFree(%p, %u, %x) intercepted\n", lpAddress, dwSize, dwFreeType);
#endif
	if(OSHavePhysicalPageSupport())
	{
		if(dwFreeType==MEM_DECOMMIT)
		{
			if(-1!=userpage_release(lpAddress, dwSize)) return 1;
		}
		else if(dwFreeType==MEM_RELEASE)
		{
			if(-1!=userpage_free(lpAddress, dwSize)) return 1;
		}
	}
	return VirtualFree(lpAddress, dwSize, dwFreeType);
}
static SIZE_T WINAPI VirtualQuery_winpatcher(LPVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwSize)
{
#if defined(_DEBUG)
	DebugPrint("Winpatcher: VirtualQuery(%p, %p, %u) intercepted\n", lpAddress, lpBuffer, dwSize);
#endif
	return VirtualQuery(lpAddress, lpBuffer, dwSize);
}
#endif /* ENABLE_USERMODEPAGEALLOCATOR */






/* The patch table: replace the specified symbols in the specified modules with the
   specified replacements. Format is:

   <--            what to replace               -->  <--  in what  -->  <--          replacements            -->
   {{ "<linker symbol>", 0, "", 0|<function addr> }, 0|<which modules>, { "<linker symbol>", <function addr> } },

   If you specify <which modules> then <function addr> is overwritten with whatever
   GetProcAddress() returns for <linker symbol>. On the hand, and usually much more
   usefully, leaving <which modules> at zero and writing in whatever the dynamic
   linker resolves for <function addr> lets the patcher look up which modules the
   dynamic linker used and to patch that instead. This helps when the implementing
   module is not constant, but it does require that the enclosing DLL is using the
   same version as everything else in the process.

   Note that not specifying modules introduces x86 or x64 dependent code and specific
   assumptions about how MSVC implements the PE image spec. The only fully portable
   method is to specify modules, plus specifying modules covers executables not built
   using the same version of MSVCRT.
*/
static ModuleListItem modules[]={
	/* NOTE: Keep these release/debug format as this is used above! */
#if 0
	/* Release and Debug MSVC6 CRTs */
	{ "MSVCRT.DLL", 0, 0 }, { "MSVCRTD.DLL", 0, 0 },
#endif
	/* Release and Debug MSVC7.0 CRTs */
	{ "MSVCR70.DLL", 0, 0 }, { "MSVCR70D.DLL", 0, 0 },
	/* Release and Debug MSVC7.1 CRTs */
	{ "MSVCR71.DLL", 0, 0 }, { "MSVCR71D.DLL", 0, 0 },
	/* Release and Debug MSVC8 CRTs */
	{ "MSVCR80.DLL", 0, 0 }, { "MSVCR80D.DLL", 0, 0 },
	/* Release and Debug MSVC9 CRTs */
	{ "MSVCR90.DLL", 0, 0 }, { "MSVCR90D.DLL", 0, 0 },
	/* Release and Debug MSVC10 CRTs */
	{ "MSVCR100.DLL", 0, 0 }, { "MSVCR100D.DLL", 0, 0 },
	{ 0, 0, 0 }
};
static ModuleListItem kernelmodule[]={
	{ "KERNEL32.DLL", 0, 0 },
	{ 0, 0, 0 }
};
static SymbolListItem nedmallocpatchtable[]={
#ifdef NEDMALLOC_H
	{ { "malloc",           0, "", 0/*(PROC) malloc */ },           modules, { "nedmalloc",      (PROC) nedmalloc      } },
	{ { "calloc",           0, "", 0/*(PROC) calloc */ },           modules, { "nedcalloc",      (PROC) nedcalloc      } },
	{ { "realloc",          0, "", 0/*(PROC) realloc*/ },           modules, { "nedrealloc",     (PROC) nedrealloc     } },
	{ { "free",             0, "", 0/*(PROC) free   */ },           modules, { "nedfree",        (PROC) nedfree        } },
	{ { "_msize",           0, "", 0/*(PROC) _msize */ },           modules, { "nedblksize",     (PROC) nedmemsize     } },
#endif
#if 0 /* Usually it's best to leave these off */
	{ { "_malloc_dbg",  0, "", 0/*(PROC) malloc */ }, modules, { "nedmalloc_dbg",  (PROC) nedmalloc_dbg  } },
	{ { "_calloc_dbg",  0, "", 0/*(PROC) calloc */ }, modules, { "nedcalloc_dbg",  (PROC) nedcalloc_dbg  } },
	{ { "_realloc_dbg", 0, "", 0/*(PROC) realloc*/ }, modules, { "nedrealloc_dbg", (PROC) nedrealloc_dbg } },
	{ { "_free_dbg",    0, "", 0/*(PROC) free   */ }, modules, { "nedfree_dbg",    (PROC) nedfree_dbg    } },
	{ { "_msize_dbg",   0, "", 0/*(PROC) free   */ }, modules, { "nedblksize_dbg", (PROC) nedblksize_dbg } },
#endif
	{ { "LoadLibraryA", 0, "", 0 }, kernelmodule, { "LoadLibraryA_winpatcher", (PROC) LoadLibraryA_winpatcher } },
	{ { "LoadLibraryW", 0, "", 0 }, kernelmodule, { "LoadLibraryW_winpatcher", (PROC) LoadLibraryW_winpatcher } },
#ifdef REPLACE_SYSTEM_ALLOCATOR
#if ENABLE_USERMODEPAGEALLOCATOR
	{ { "VirtualAlloc", 0, "", 0 }, kernelmodule, { "VirtualAlloc_winpatcher", (PROC) VirtualAlloc_winpatcher } },
	{ { "VirtualFree",  0, "", 0 }, kernelmodule, { "VirtualFree_winpatcher",  (PROC) VirtualFree_winpatcher  } },
	{ { "VirtualQuery", 0, "", 0 }, kernelmodule, { "VirtualQuery_winpatcher", (PROC) VirtualQuery_winpatcher } },
#endif
#endif
	{ { 0, 0, "", 0 }, 0, { 0, 0 } }
};
#ifdef NEDMALLOC_H
/* Thunks for nedmalloc */
static void *nedmalloc_dbg(size_t size, int type, const char *filename, int lineno)             { return nedmalloc(size); }
static void *nedcalloc_dbg(size_t no, size_t size, int type, const char *filename, int lineno)  { return nedcalloc(no, size); }
static void *nedrealloc_dbg(void *ptr, size_t size, int type, const char *filename, int lineno) { return nedrealloc(ptr, size); }
static void nedfree_dbg(void *ptr, int type)                                                    { nedfree(ptr); }
static size_t nedblksize_dbg(void *ptr, int type)                                               { return nedmemsize(ptr); }

/* Here come some fun! Windows is unusual in that various DLLs loaded by processes may be
linked to any one of the MSVCRTs listed in the patch table above - which is twelve different
options. Each MSVCRT runs its own separate CRT heap and is generally incapable of handling
blocks from a MSVCRT not its own, so we need to figure out specifically which system allocator
function to call based on what is doing the call. Painful, but not much choice! */
extern HANDLE sym_myprocess;
extern VOID (WINAPI *RtlCaptureContextAddr)(PCONTEXT);
extern void DeinitSym(void) THROWSPEC;
HANDLE sym_myprocess;
VOID (WINAPI *RtlCaptureContextAddr)(PCONTEXT)=(VOID (WINAPI *)(PCONTEXT)) -1;
void DeinitSym(void) THROWSPEC
{
	if(sym_myprocess)
	{
		SymCleanup(sym_myprocess);
		CloseHandle(sym_myprocess);
		sym_myprocess=0;
	}
}
#pragma optimize("g", off)
static int ExceptionFilter(unsigned int code, struct _EXCEPTION_POINTERS *ep, CONTEXT *ct) THROWSPEC
{
	*ct=*ep->ContextRecord;
	return EXCEPTION_EXECUTE_HANDLER;
}
static DWORD64 __stdcall GetModBase(HANDLE hProcess, DWORD64 dwAddr) THROWSPEC
{
	DWORD64 modulebase;
	// Try to get the module base if already loaded, otherwise load the module
	modulebase=SymGetModuleBase64(hProcess, dwAddr);
	if(modulebase)
		return modulebase;
	else
	{
		MEMORY_BASIC_INFORMATION stMBI ;
		if ( 0 != VirtualQueryEx ( hProcess, (LPCVOID)(size_t)dwAddr, &stMBI, sizeof(stMBI)))
		{
			int n;
			DWORD dwPathLen=0, dwNameLen=0 ;
			TCHAR szFile[ MAX_PATH ], szModuleName[ MAX_PATH ] ;
			MODULEINFO mi={0};
			dwPathLen = GetModuleFileName ( (HMODULE) stMBI.AllocationBase , szFile, MAX_PATH );
			dwNameLen = GetModuleBaseName (hProcess, (HMODULE) stMBI.AllocationBase , szModuleName, MAX_PATH );
			for(n=dwNameLen; n>0; n--)
			{
				if(szModuleName[n]=='.')
				{
					szModuleName[n]=0;
					break;
				}
			}
			if(!GetModuleInformation(hProcess, (HMODULE) stMBI.AllocationBase, &mi, sizeof(mi)))
			{
				//fxmessage("WARNING: GetModuleInformation() returned error code %d\n", GetLastError());
			}
			if(!SymLoadModule64 ( hProcess, NULL, (PSTR)( (dwPathLen) ? szFile : 0), (PSTR)( (dwNameLen) ? szModuleName : 0),
				(DWORD64) mi.lpBaseOfDll, mi.SizeOfImage))
			{
				//fxmessage("WARNING: SymLoadModule64() returned error code %d\n", GetLastError());
			}
			//fxmessage("%s, %p, %x, %x\n", szFile, mi.lpBaseOfDll, mi.SizeOfImage, (DWORD) mi.lpBaseOfDll+mi.SizeOfImage);
			modulebase=SymGetModuleBase64(hProcess, dwAddr);
			return modulebase;
		}
	}
	return 0;
}
static HMODULE DoFindMSVCRTForCaller(void)
{
	int i;
	HANDLE mythread=(HANDLE) GetCurrentThread();
	STACKFRAME64 sf={ 0 };
	CONTEXT ct={ 0 };
	if(!sym_myprocess)
	{
		DWORD symopts;
		DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(), &sym_myprocess, 0, FALSE, DUPLICATE_SAME_ACCESS);
		symopts=SymGetOptions();
		SymSetOptions(symopts /*| SYMOPT_DEFERRED_LOADS*/ | SYMOPT_LOAD_LINES);
		SymInitialize(sym_myprocess, NULL, TRUE);
		atexit(DeinitSym);
	}
	ct.ContextFlags=CONTEXT_FULL;

	// Use RtlCaptureContext() if we have it as it saves an exception throw
	if((VOID (WINAPI *)(PCONTEXT)) -1==RtlCaptureContextAddr)
		RtlCaptureContextAddr=(VOID (WINAPI *)(PCONTEXT)) GetProcAddress(GetModuleHandle(L"kernel32"), "RtlCaptureContext");
	if(RtlCaptureContextAddr)
		RtlCaptureContextAddr(&ct);
	else
	{	// This is nasty, but it works
		__try
		{
			int *foo=0;
			*foo=78;
		}
		__except (ExceptionFilter(GetExceptionCode(), GetExceptionInformation(), &ct))
		{
		}
	}

	sf.AddrPC.Mode=sf.AddrStack.Mode=sf.AddrFrame.Mode=AddrModeFlat;
#if !(defined(_M_AMD64) || defined(_M_X64))
	sf.AddrPC.Offset   =ct.Eip;
	sf.AddrStack.Offset=ct.Esp;
	sf.AddrFrame.Offset=ct.Ebp;
#else
	sf.AddrPC.Offset   =ct.Rip;
	sf.AddrStack.Offset=ct.Rsp;
	sf.AddrFrame.Offset=ct.Rbp; // maybe Rdi?
#endif
	for(;;)
	{
		IMAGEHLP_MODULE64 ihm={ sizeof(IMAGEHLP_MODULE64) };
		if(!StackWalk64(
#if !(defined(_M_AMD64) || defined(_M_X64))
			IMAGE_FILE_MACHINE_I386,
#else
			IMAGE_FILE_MACHINE_AMD64,
#endif
			sym_myprocess, mythread, &sf, &ct, NULL, SymFunctionTableAccess64, GetModBase, NULL))
			break;
		if(0==sf.AddrPC.Offset)
			break;
		if(SymGetModuleInfo64(sym_myprocess, sf.AddrPC.Offset, &ihm))
		{ // Is this me? If so keep going up the stack until it isn't
			ModuleListItem *module;
			if((HMODULE) ihm.BaseOfImage==MyModuleBase)
				continue;
			DebugPrint("Found caller of malloc function at %p (%s)\n", ihm.BaseOfImage, ihm.ModuleName);
			for(module=modules; module->into; module++)
			{
				ULONG size;
				PIMAGE_IMPORT_DESCRIPTOR desc = 0;
				if((HMODULE)(size_t)-1==module->intoAddr)
					continue;
				desc = (PIMAGE_IMPORT_DESCRIPTOR) MyImageDirectoryEntryToData((PVOID) ihm.BaseOfImage, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &size);
				if(!desc)
					continue;
				for (; desc->Name; desc++) {
					PSTR modname = (PSTR)((PBYTE) ihm.BaseOfImage + desc->Name);
					int modnamecmp = lstrcmpiA(modname, module->into);
					if (modnamecmp>0) 
						break;
					if (0==modnamecmp) {
						DebugPrint("Module %p (%s) was originally linked to %s\n", ihm.BaseOfImage, ihm.ModuleName, module->into);
						return (HMODULE) module->intoAddr;
					}
				}
			}
		}
	}
	DebugPrint("FATAL ERROR: Failed to walk up the stack of the caller!\n");
	abort();
	return (HMODULE) 0;
}
#pragma optimize("g", on)
static HMODULE FindMSVCRTForCaller(void)
{
	/* If there is only one MSVCRT in this process, call that directly. Else do a stack backtrace to
	find the MSVCRT we ought to use. */
	ModuleListItem *module;
	HMODULE ret=0;
	for(module=modules; module->into; module++)
	{
		if(module->intoAddr && (void *)-1!=module->intoAddr)
		{
			if(ret) /* We have more than one MSVCRT, so search */
				return DoFindMSVCRTForCaller();
			ret=module->intoAddr;
		}
	}
	if(ret) return ret;
	DebugPrint("FATAL ERROR: Failed to find any patched MSVCRT at all!\n");
	abort();
	return (HMODULE) 0;
}
static void *sysmallocX(size_t size)
{
	return ((void * (*)(size_t))GetProcAddress(FindMSVCRTForCaller(), "malloc"))(size);
}
static void *syscallocX(size_t no, size_t size)
{
	return ((void * (*)(size_t, size_t))GetProcAddress(FindMSVCRTForCaller(), "calloc"))(no, size);
}
static void *sysreallocX(void *ptr, size_t size)
{
	return ((void * (*)(void *, size_t))GetProcAddress(FindMSVCRTForCaller(), "realloc"))(ptr, size);
}
static void sysfreeX(void *ptr)
{
	((void   (*)(void *))GetProcAddress(FindMSVCRTForCaller(), "free"))(ptr);
}
static size_t sysblksizeX(void *ptr)
{
	return ((size_t (*)(void *))GetProcAddress(FindMSVCRTForCaller(), "_msize"))(ptr);
}
#endif
int PatchInNedmallocDLL(void) THROWSPEC
{
	static int UsingReleaseMSVCRT, UsingDebugMSVCRT;
	Status ret={SUCCESS};
#ifdef NEDMALLOC_H
	if(!UsingReleaseMSVCRT && !UsingDebugMSVCRT)
	{
		sysmalloc=sysmallocX;
		syscalloc=syscallocX;
		sysrealloc=sysreallocX;
		sysfree=sysfreeX;
		sysblksize=sysblksizeX;
	}
#endif
	ret=WinPatcher(nedmallocpatchtable, 1, &UsingReleaseMSVCRT, &UsingDebugMSVCRT);
#if defined(_DEBUG)
	DebugPrint("Winpatcher: UsingReleaseMSVCRT=%d, UsingDebugMSVCRT=%d\n", UsingReleaseMSVCRT, UsingDebugMSVCRT);
#endif
	if(ret.code<0)
	{
		TCHAR buffer[4096];
		MakeReportFromStatus(buffer, sizeof(buffer)/sizeof(TCHAR), &ret);
#if defined(_DEBUG)
		DebugPrint("Winpatcher: DLL Process Attach Failed with %s\n", buffer);
#endif
		MessageBox(NULL, buffer, __T("Error"), MB_OK);
		return FALSE;
	}
	return TRUE;
}
int DepatchInNedmallocDLL(void) THROWSPEC
{
	Status ret={SUCCESS};
	ret=WinPatcher(nedmallocpatchtable, 0, 0, 0);
	if(ret.code<0)
	{
		TCHAR buffer[4096];
		MakeReportFromStatus(buffer, sizeof(buffer)/sizeof(TCHAR), &ret);
#if defined(_DEBUG)
		DebugPrint("Winpatcher: DLL Process Detach Failed with %s\n", buffer);
#endif
		MessageBox(NULL, buffer, __T("Error"), MB_OK);
		return FALSE;
	}
	return TRUE;
}

LONG CALLBACK ProcessExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
{
	Status ret={SUCCESS};
	ExceptionToStatus(&ret, ExceptionInfo->ExceptionRecord->ExceptionCode, ExceptionInfo);
	return EXCEPTION_CONTINUE_SEARCH;
}


/* The DLL entry function for nedmalloc. This is called by the dynamic linker
before absolutely everything else - including the CRT */
BOOL WINAPI
_DllMainCRTStartup(
        HANDLE  hDllHandle,
        DWORD   dwReason,
        LPVOID  lpreserved
        );
BOOL WINAPI _CRT_INIT(
        HANDLE  hDllHandle,
        DWORD   dwReason,
        LPVOID  lpreserved
        );
//#pragma optimize("", off)
/* We split DllPreMainCRTStartup to avoid an annoying bug on the x64 compiler in /O2
whereby it inserts a security cookie check before we've initialised support for it, thus
provoking a failure */
static PVOID ProcessExceptionHandlerH;
static __declspec(noinline) BOOL DllPreMainCRTStartup2(HMODULE myModuleBase, DWORD dllcode, LPVOID *isTheDynamicLinker)
{
	BOOL ret=TRUE;
	if(!MyModuleBase) MyModuleBase=myModuleBase;
	if(DLL_PROCESS_ATTACH==dllcode)
	{
#ifdef REPLACE_SYSTEM_ALLOCATOR
#if defined(_DEBUG)
		DebugPrint("Winpatcher: patcher DLL loaded at %p\n", myModuleBase);
#if 0	/* Seems to get upset if kernel32 isn't initialised :( */
		if(!(ProcessExceptionHandlerH=AddVectoredExceptionHandler(1, ProcessExceptionHandler)))
		{
			TCHAR buffer[4096];
			Status ret={SUCCESS};
			MKSTATUSWIN(ret);
			MakeReportFromStatus(buffer, sizeof(buffer)/sizeof(TCHAR), &ret);
			DebugPrint("Winpatcher: Failed to install process exception hook due to: %s\n", buffer);
			return FALSE;
		}
		DebugPrint("Winpatcher: installed process exception hook with handle %p\n", ProcessExceptionHandlerH);
#endif
#endif /* defined(_DEBUG) */
#endif /* defined(REPLACE_SYSTEM_ALLOCATOR) */
#ifdef ENABLE_LARGE_PAGES
		/* Attempt to enable SeLockMemoryPrivilege */
		{
			HANDLE token;
			if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))
			{
				TOKEN_PRIVILEGES privs={1};
				if(LookupPrivilegeValue(NULL, SE_LOCK_MEMORY_NAME, &privs.Privileges[0].Luid))
				{
					privs.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;
					if(!AdjustTokenPrivileges(token, FALSE, &privs, 0, NULL, NULL) || GetLastError()!=S_OK)
					{
#if defined(_DEBUG)
						DebugPrint("Winpatcher: Failed to enable SeLockMemoryPrivilege. Large pages will not be used.\n");
#endif
						OutputDebugStringA("Winpatcher: Failed to enable SeLockMemoryPrivilege. Large pages will not be used.\n");
					}
				}
				CloseHandle(token);
			}
		}
#endif
#ifdef REPLACE_SYSTEM_ALLOCATOR
		if(!PatchInNedmallocDLL())
			return FALSE;
#endif
	}
	/* Invoke the CRT's handler which does atexit() etc */
	ret=_CRT_INIT(myModuleBase, dllcode, isTheDynamicLinker);
	if(DLL_THREAD_DETACH==dllcode)
	{	/* Destroy the thread cache for all known pools */
#ifdef NEDMALLOC_H
		nedpool **pools=nedpoollist();
		if(pools)
		{
			nedpool **pool;
			for(pool=pools; *pool; ++pool)
				neddisablethreadcache(*pool);
			nedfree(pools);
		}
		neddisablethreadcache(0);
#endif
	}
	else if(DLL_PROCESS_DETACH==dllcode)
	{
#ifdef NEDMALLOC_H
		nedpool **pools=nedpoollist();
#if defined(_DEBUG)
		DebugPrint("Winpatcher: patcher DLL being kicked out from %p\n", myModuleBase);
#endif
		if(pools)
		{
			nedpool **pool;
			for(pool=pools; *pool; ++pool)
				nedflushlogs(*pool, 0);
			nedfree(pools);
		}
		nedflushlogs(0, 0);
#endif
		/* You can enable the below if you want, but you probably don't */
		/*if(!DepatchInNedmallocDLL())
			return FALSE;*/
#ifdef _DEBUG
#if 0
		if(!RemoveVectoredExceptionHandler(ProcessExceptionHandlerH))
			return FALSE;
#endif
#endif
	}
	return ret;
}

BOOL APIENTRY DllPreMainCRTStartup(HMODULE myModuleBase, DWORD dllcode, LPVOID *isTheDynamicLinker)
{
	if(DLL_PROCESS_ATTACH==dllcode)
		__security_init_cookie();	/* For /GS support */
	return DllPreMainCRTStartup2(myModuleBase, dllcode, isTheDynamicLinker);
}

#if defined(__cplusplus)
}
#endif
#endif
